from typing import List, Optional, Dict, Any
from pydantic import BaseModel, Field, field_validator
from datetime import datetime


class TaskScenarioBase(BaseModel):
    """任务场景基础模型"""
    name: str = Field(..., min_length=1, max_length=200, description="场景名称")
    description: Optional[str] = Field(None, description="场景描述")
    drone_type_requirements: Optional[List[Dict[str, Any]]] = Field(None, description="适用无人机类型要求")
    detection_target_ids: Optional[List[int]] = Field(None, description="关联的检测目标ID列表")
    default_route_logic: Optional[Dict[str, Any]] = Field(None, description="默认航线逻辑配置")
    detection_model_ids: Optional[List[int]] = Field(None, description="关联的检测模型ID列表")
    permission_config: Optional[Dict[str, Any]] = Field(None, description="人员权限配置")
    is_active: bool = Field(True, description="是否激活")


class TaskScenarioCreate(TaskScenarioBase):
    """创建任务场景请求模型"""
    created_from_template_id: Optional[int] = Field(None, description="创建自哪个模板ID")
    
    @field_validator('drone_type_requirements', 'default_route_logic', 'permission_config')
    def validate_json_fields(cls, v):
        # 这些字段在数据库中存储为JSON字符串，但在API中使用Python对象
        return v


class TaskScenarioUpdate(BaseModel):
    """更新任务场景请求模型"""
    name: Optional[str] = Field(None, min_length=1, max_length=200, description="场景名称")
    description: Optional[str] = Field(None, description="场景描述")
    drone_type_requirements: Optional[List[Dict[str, Any]]] = Field(None, description="适用无人机类型要求")
    detection_target_ids: Optional[List[int]] = Field(None, description="关联的检测目标ID列表")
    default_route_logic: Optional[Dict[str, Any]] = Field(None, description="默认航线逻辑配置")
    detection_model_ids: Optional[List[int]] = Field(None, description="关联的检测模型ID列表")
    permission_config: Optional[Dict[str, Any]] = Field(None, description="人员权限配置")
    is_active: Optional[bool] = Field(None, description="是否激活")


class TaskScenarioSchema(TaskScenarioBase):
    """任务场景响应模型"""
    id: int = Field(..., description="场景ID")
    scenario_type: str = Field(..., description="场景类型：preset(预设模板)/custom(自定义)")
    created_from_template_id: Optional[int] = Field(None, description="创建自哪个模板ID")
    created_at: datetime = Field(..., description="创建时间")
    updated_at: datetime = Field(..., description="更新时间")
    detection_targets: Optional[List[Dict[str, Any]]] = Field(None, description="检测目标信息")
    
    @field_validator('created_at', 'updated_at')
    @classmethod
    def format_datetime(cls, v):
        # 格式化时间，只显示到秒
        if isinstance(v, datetime):
            return v.replace(microsecond=0)
        return v
    
    class Config:
        from_attributes = True


class TaskScenarioWithTemplate(TaskScenarioSchema):
    """包含模板信息的任务场景响应模型"""
    created_from_template: Optional['TaskScenarioSchema'] = Field(None, description="创建自的模板信息")


# 更新前向引用
TaskScenarioWithTemplate.model_rebuild()


class TaskScenarioList(BaseModel):
    """任务场景列表响应模型"""
    items: List[TaskScenarioSchema] = Field(..., description="场景列表")
    total: int = Field(..., description="总数")
    page: int = Field(..., description="当前页码")
    page_size: int = Field(..., description="每页大小")


class CloneScenarioRequest(BaseModel):
    """复制场景请求模型"""
    name: str = Field(..., min_length=1, max_length=200, description="新场景名称")
    description: Optional[str] = Field(None, description="新场景描述")